import prettytable
import requests
from prettytable import PrettyTable


class Ticket(object):
    def __init__(self):
        """初始函数"""
        self.cname = []
        self.ename = []
        self.from_station_cname = ""
        self.from_station_ename = ""
        self.to_station_cname = ""
        self.to_station_ename = ""
        self.train_date = ""
        self.getPlaceList()
        pass

    def getPlaceList(self):
        """获取所有火车站点信息"""
        url = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9217"
        r = requests.get(url)
        tlist = r.text.split('@')[1:]  # 切片
        tlist[-1] = tlist[-1][:-2]  # 删除多余元素
        for i in tlist:
            place = i.split('|')
            # place 首个数据 ['bjb', '北京北', 'VAP', 'beijingbei', 'bjb', '0']
            self.cname.append(place[1])
            self.ename.append(place[2])

    def getInput(self):
        self.from_station_cname = input("出发地:")
        self.from_station_ename = self.ename[self.cname.index(self.from_station_cname)]
        # print(self.from_station_ename)
        self.to_station_cname = input("目的地:")
        self.to_station_ename = self.ename[self.cname.index(self.to_station_cname)]
        # print(self.to_station_ename)
        self.train_date = input("出发时间:")

    def getTrainMessage(self):
        def prettyName(name):
            return '{name:^{len}}'.format(name=name, len=8 - len(name.encode('GBK')) + len(name))

        url = "https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={0}&leftTicketDTO.from_station={1}&leftTicketDTO.to_station={2}&purpose_codes=ADULT".format(
            self.train_date, self.from_station_ename, self.to_station_ename)
        headers = {
            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.43",
            'Cookie': '_uab_collina=163889964564524796779452; JSESSIONID=FACB2E7A10C00C04C7D618835ACD792F; highContrastMode=defaltMode; guidesStatus=off; cursorStatus=off; _jc_save_fromStation=%u6E29%u5DDE%2CRZH; _jc_save_toStation=%u957F%u6C99%2CCSQ; _jc_save_wfdc_flag=dc; _jc_save_fromDate=2021-12-11; _jc_save_toDate=2021-12-11; BIGipServerpassport=870842634.50215.0000; BIGipServerotn=4124508426.50210.0000; RAIL_EXPIRATION=1639475886213; RAIL_DEVICEID=BZpLSX2cxUcxWENKcZp0rIPCuq1QsTTWeQBmDOfBdiEd4KK20XR7V2P3IFEzeeUu-8-c9mBNECNpeVWcUUgeomREWYsEabJv0yxZANVj-JG0CPbWcj9163KX3Npqsm_jcsl00S-kqTQcmTxAK2veQsckjdmDxDb0; route=9036359bb8a8a461c164a04f8f50b252'}
        r = requests.get(url, headers=headers)
        # 参考数据 wUBgKts3zTc0WO%2F5javfjxWEf7J6dut7TW3oy919n4DvjKX%2B8HlMdVE2WkmVnM0e6A6iYBSs5Lyw%0A97FBe%2FMM0X0qjYcb762GvgDyD2C7OhYSMrFs7aqX0FnZ4ULGRnbj5Q1J3jO%2BFPRyJ6HhkvIsC%2BDI%0AzEab5Y8kPp1%2Bc3GAZj4DGjDnJGGoa1hyAXrUIg%2FrRxfgwTmlFuxc1NpljlVnnWMurrt2XYFvHJYE%0AAGGfoyeOfI5EHuxL5dHdnByeKh2QnEz%2FP1a9eMBE9WLU2o%2B4TfmvCt4IWbreuXlPnRneWobBCq7z%0ADhEdBZULLvU%3D|预订|71000G23440F|G2344|NFZ|NGH|CWQ|VRH|14:54|20:13|05:19|Y|HzSIBx3efqOr5J4gbMQBq4ASJWcGA8NITjKz97t7MI%2BFs0P6|20211211|3|Z1|12|25|1|0|||||||||||无|2|4||O0M090|OM9|1|1||O041150000M0687000029128850004|0|||||1|#0#0#0||7
        message = r.json()['data']['result']
        table = PrettyTable(align='c', hrules=prettytable.ALL)
        table.field_names = [prettyName('车次'), prettyName('出发站'), prettyName('到达站'), prettyName('出发时间'),
                             prettyName('到达时间'), prettyName('历时'), prettyName('特等'), prettyName('一等'),
                             prettyName('二等'), prettyName('高级软卧'), prettyName('软卧'),
                             prettyName('动卧'), prettyName('硬卧'), prettyName('硬座'), prettyName('无座')]
        for m in message:
            train_message = []
            test = m.split('|')
            train_message.append(test[3])  # 车次
            train_message.append(self.from_station_cname)  # 出发站
            train_message.append(self.to_station_cname)  # 到达站
            train_message.append(test[8])  # 出发时间
            train_message.append(test[9])  # 到达时间
            train_message.append(test[10])  # 历时
            train_message.append(test[32] if test[32] != '' else '--')  # 商务座
            train_message.append(test[31] if test[31] != '' else '--')  # 一等座
            train_message.append(test[30] if test[30] != '' else '--')  # 二等座
            train_message.append(test[21] if test[21] != '' else '--')  # 高级软卧
            train_message.append(test[23] if test[23] != '' else '--')  # 软卧一等座
            train_message.append(test[33] if test[33] != '' else '--')  # 动卧
            train_message.append(test[28] if test[28] != '' else '--')  # 硬卧二等座
            train_message.append(test[29] if test[29] != '' else '--')  # 硬座
            train_message.append(test[26] if test[26] != '' else '--')  # 无座
            table.add_row(train_message)
        print(table)


def main():
    ticket = Ticket()
    ticket.getInput()
    ticket.getTrainMessage()
    pass


if __name__ == '__main__':
    main()
